<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    destroyOnClose
    :confirmLoading="confirmLoading"
    :footer="hasPerm('emsOrder:edit') ? undefined : null"
    @cancel="handleCancel">
    
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>
          
          <a-col :span="12" v-show="false">
            <a-form-item
              label="主键"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入主键"
                       v-decorator="['orderId', {rules: [{required: false, message: '请输入主键！'}]}]"
                       :disabled="disabled"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-show="false">
            <a-form-item
              label="父订单"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入父订单"
                       v-decorator="['orderParentId', {rules: [{required: false, message: '请输入父订单！'}]}]"
                       :disabled="disabled"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-show="false">
            <a-form-item
              label="父订单"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入父订单"
                       v-decorator="['orderPids', {rules: [{required: false, message: '请输入父订单pids！'}]}]"
                       :disabled="disabled"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="生产单号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入订单号" v-decorator="['orderNumber']"
                       :disabled="disabled"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="国家"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-select
                @focus="getguojia"
                :disabled="disabled"
                placeholder="请选择"
                style="width: 272px"
                v-decorator="['countryCode', {rules: [{required: true, message: '请选择国家！'}]}]"
              >
                <a-select-option :value="item.id" v-for="(item, index) in guojiaList" :key="index">{{ item.value }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="下发时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-date-picker placeholder="请输入下发时间"
                             v-decorator="['issueTime', {rules: [{required: true, message: '请输入下发时间！'}]}]"
                             :disabled="disabled"
                             style="width: 100%"
                             format="YYYY-MM-DD HH:mm:ss"
                             value-format="YYYY-MM-DD HH:mm:ss"
                             :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="预计完成时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-date-picker placeholder="请输入预计完成时间"
                             v-decorator="['estimateCompletionTime', {rules: [{required: true, message: '请输入预计完成时间！'}]}]"
                             :disabled="disabled"
                             style="width: 100%"
                             format="YYYY-MM-DD HH:mm:ss"
                             value-format="YYYY-MM-DD HH:mm:ss"
                             :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-show="false">
            <a-form-item
              label="订单类型"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入订单类型"
                       v-decorator="['orderType', {rules: [{required: true, message: '请输入订单类型！'}]}]"
                       :disabled="disabled"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="归属子公司"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-select placeholder="请输入归属子公司"
                        v-decorator="['targetOrgId', {rules: [{required: true, message: '请输入归属子公司！'}]}]"
                        :disabled="disabled">
                <a-select-option :value="id"
                                 v-for="{id, name} in $util.getOrgList([$businessEnum.ORG_TYPE_ENUM.COMPANY.id])">
                  {{ name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="是否是海外仓"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <!--              <a-input placeholder="请输入是否是海外仓" v-decorator="['isOverseasStore', {rules: [{required: true, message: '请输入是否是海外仓！'}]}]"-->
              <!--                       :disabled="disabled"/>-->
              <a-select placeholder="请输入是否是海外仓"
                        v-decorator="['isOverseasStore', {rules: [{required: true, message: '请输入是否是海外仓！'}],initialValue:'N'}]"
                        :disabled="disabled">
                <a-select-option value="Y">是</a-select-option>
                <a-select-option value="N">否</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item
              label="接收时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-date-picker placeholder="请输入接收时间"
                             v-decorator="['receiveTime', {rules: [{required: true, message: '请输入接收时间！'}],initialValue:moment('00:00:00', 'HH:mm:ss')}]"
                             :disabled="disabled"
                             style="width: 100%"
                             format="YYYY-MM-DD HH:mm:ss"
                             value-format="YYYY-MM-DD HH:mm:ss"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="排序"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input-number
							style="width: 100%;"
                placeholder="请输入排序"
								:min="0"
                v-decorator="['sort', {rules: [{required: true, message: '请输入排序！'}]}]"           
              />              
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item
              label="附件"
              :labelCol="labelColBlock"
              :wrapperCol="wrapperColBlock"
              has-feedback="">
              <a-input
                placeholder="请上传附件"
                v-decorator="['file', {rules: [{required: true, message: '请上传附件！'}]}]"
                v-show="false"
              />
              <fc-upload :file-list="fileList" :handle-file-list-string-change="handleFileListStringChange"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="24">
            <!-- 22--{{ fileName }} -->
            <a-form-item
              v-if="form.getFieldValue('file')"
              label="预览"
              :labelCol="labelColBlock"
              :wrapperCol="wrapperColBlock"
              has-feedback="">
              <!-- <a>{{form.getFieldValue('file')}}</a> -->
              <a :download="fileName"
                 :href="`${$store.state.baseUrl}/sysFileInfo/preview?id=${form.getFieldValue('file')}`">下载 / 预览</a>
            </a-form-item>
          </a-col>
          
          <a-col :span="24">
            <a-form-item
              label="备注"
              :labelCol="labelColBlock"
              :wrapperCol="wrapperColBlock"
              has-feedback="">
              <!-- 富文本不能用v-decorator,所以用v-model绑定 -->
              <antd-editor
                v-if="1"
                :uploadConfig="editorUploadConfig"
                v-model="remark"
                @onchange="changeEditor"
                @oninit="getEditor"
              />
              <div
                v-else
                style="min-width:550px; height:400px; overflow:auto; border:1px solid #aaa; padding:10px"
                v-html="remark"
              >
              </div>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-if="false">
            <a-form-item
              label="进度状态"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入进度状态"
                       v-decorator="['progressStatus', {rules: [{required: true, message: '请输入进度状态！'}]}]"
                       :disabled="disabled"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-if="false">
            <a-form-item
              label="生产进度"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入生产进度"
                       v-decorator="['produceProgress', {rules: [{required: true, message: '请输入生产进度！'}]}]"
                       :disabled="disabled"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-if="false">
            <a-form-item
              label="状态（字典 0正常 1冻结 2删除）"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入状态（字典 0正常 1冻结 2删除）"
                       v-decorator="['status', {rules: [{required: true, message: '请输入状态（字典 0正常 1冻结 2删除）！'}]}]"
                       :disabled="disabled"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-if="false">
            <a-form-item
              label="创建时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入创建时间"
                       v-decorator="['createTime', {rules: [{required: true, message: '请输入创建时间！'}]}]"
                       :disabled="disabled"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-if="false">
            <a-form-item
              label="创建人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入创建人"
                       v-decorator="['createUser', {rules: [{required: true, message: '请输入创建人！'}]}]"
                       :disabled="disabled"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-if="false">
            <a-form-item
              label="更新时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入更新时间"
                       v-decorator="['updateTime', {rules: [{required: true, message: '请输入更新时间！'}]}]"
                       :disabled="disabled"/>
            </a-form-item>
          </a-col>
          
          <a-col :span="12" v-if="false">
            <a-form-item
              label="更新人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-input placeholder="请输入更新人"
                       v-decorator="['updateUser', {rules: [{required: true, message: '请输入更新人！'}]}]"
                       :disabled="disabled"/>
            </a-form-item>
          </a-col>
        
        </a-row>
      </a-form>
    </a-spin>
    
    
    <template slot="footer">
      <div>
        <a-button type="white" @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleSubmit">确定</a-button>
      </div>
    </template>
  </a-modal>
</template>

<script>
import {edit, getDetailApi} from '@/api/modular/main/emsorder/emsOrderManage'
import FcUpload from '@/components/FCUpload/FcUploadPDF'
import Vue from 'vue'
import {ACCESS_TOKEN} from '@/store/mutation-types'
import moment from 'moment'
import {AntdEditor} from '@/components'
import {sysFileInfoUpload} from '@/api/modular/system/fileManage'

export default {
  components: {
    FcUpload,
    AntdEditor
  },
  mounted() {
    this.getguojia()
  },
  data() {
    return {
      labelCol: {
        xs: {span: 24},
        sm: {span: 6}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 15}
      },
      labelColBlock: {
        xs: {span: 24},
        sm: {span: 3}
      },
      wrapperColBlock: {
        xs: {span: 24},
        sm: {span: 20}
      },
      editorUploadConfig: {
        method: 'http',
        callback: this.editorUploadImage
      },
      editor: '',
      fileName: '',
      remark: '',
      guojiaList: [],
      editorContentText: '',
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      fileList: [],
      disabled: false,
			title:"",
    }
  },
  methods: {
    moment,
    fcsuccess(url) {
      this.form.setFieldsValue({image: url})
    },
    async edit(record) {
      this.visible = true
      this.disabled = false
      console.log('record', record)
			this.title = `订单详情（${record.orderNumber}）`
      this.remark = record.remark
      await this.getImgDetail(record.file)
      setTimeout(() => {
        this.form.setFieldsValue({
          orderId: record.orderId,
          orderParentId: record.orderParentId,
          orderNumber: record.orderNumber,
          orderType: record.orderType,
          orgId: record.orgId,
          targetOrgId: record.targetOrgId,
          isOverseasStore: record.isOverseasStore,
          countryCode: record.countryCode,
          file: record.file,
          sort: record.sort,
          progressStatus: record.progressStatus,
          produceProgress: record.produceProgress,
          issueTime: moment(record.issueTime),
          estimateCompletionTime: moment(record.estimateCompletionTime),
          receiveTime: moment(record.receiveTime),
          status: record.status,
          createTime: record.createTime,
          createUser: record.createUser,
          updateTime: record.updateTime,
          updateUser: record.updateUser,
        })
      }, 200)
      
      // 还需要将数据中的图片格式化
      const token = Vue.ls.get(ACCESS_TOKEN)
      this.$nextTick(() => {
        setTimeout(() => {
          this.fileList = record.file.split(',').map(fileID => {
            return {
              uid: fileID,
              name: this.fileName || '加载中...',
              status: 'done',
              url: `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${fileID}&token=${token}`,
              fileID: fileID
            }
          })
        }, 500)
      })
    },
    getImgDetail(id) {
      new Promise((resolve, reject) => {
        getDetailApi({id}).then(res => {
          console.log('详情', res.data)
          this.fileName = res.data.fileOriginName
          console.log('fileName', this.fileName)
        })
      })
    },
    getEditor(editor) {
      this.editor = editor
    },
    getguojia() {
      this.axios.get('/sysDictData/list?typeCode=COUNTRY').then((res) => {
        this.guojiaList = res.data
      })
    },
    changeEditor(html, ele) {
      this.form.setFieldsValue({
        remark: html
      })
      this.editorContentText = ele.text()
    },
    // 富文本
    editorUploadImage(files, insert) {
      const formData = new FormData()
      files.forEach(file => {
        formData.append('file', file)
      })
      sysFileInfoUpload(formData).then((res) => {
        if (res.success) {
          insert(process.env.VUE_APP_API_BASE_URL + '/sysFileInfo/preview?id=' + res.data)
        } else {
          this.$message.error('编辑器上传图片失败：' + res.message)
        }
      })
    },
    disabledShow(record) {
      this.edit(record)
      this.disabled = true
    },
    handleSubmit() {
      console.log('handleSubmit')
      if (this.remark == '') {
        this.$message.error("请输入备注")
        return
      }
      const {form: {validateFields}} = this
      this.confirmLoading = true
      
      validateFields((errors, values) => {
        console.log(errors, values)
        let _values = Object.assign({}, values)
        for (let key in _values) {
          let value = _values[key]
          if (value && typeof value === 'object') {
            _values[key] = value.format('YYYY-MM-DD HH:mm:ss')
          }
        }
        if (!errors) {
          edit({remark: this.remark, ..._values}).then((res) => {
            this.confirmLoading = false
            if (res.success) {
              this.$message.success('编辑成功')
              this.handleCancel()
              this.$emit('ok', values)
            } else {
              this.$message.info('编辑失败：' + res.message)
            }
          }).finally((res) => {
            this.confirmLoading = false
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.form.resetFields()
      this.remark = ''
      this.fileName = ''
      this.editor = ''
      this.editorContentText = ''
      this.visible = false
    },
    // upload
    handleFileListStringChange(fileListString) {
      this.form.setFieldsValue({file: fileListString})
    }
  }
}
</script>
